package cloud.ben.smallscalepigfarmmanagementsystem.config;

import cloud.ben.smallscalepigfarmmanagementsystem.filter.AuthorizationLoginFilter;
import cloud.ben.smallscalepigfarmmanagementsystem.filter.LoginFilter;
import cloud.ben.smallscalepigfarmmanagementsystem.handler.JwtAccessDeniedHandler;
import cloud.ben.smallscalepigfarmmanagementsystem.handler.JwtAuthenticationEntryPoint;
import cloud.ben.smallscalepigfarmmanagementsystem.service.impl.UserAuthServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @Author: Ben
 * @Date: 2022/3/1 21:58
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Autowired
    private UserAuthServiceImpl userAuthService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public void configure(WebSecurity web) throws Exception {
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                // 其他都放行了
                .antMatchers("/admin/**").authenticated()
                .anyRequest().permitAll()
                .and()
                .addFilter(new LoginFilter(authenticationManager(),stringRedisTemplate))   //自定义认证过滤器
                .addFilter(new AuthorizationLoginFilter(authenticationManager(),stringRedisTemplate))
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling().authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                .accessDeniedHandler(new JwtAccessDeniedHandler());      //添加无权限时的处理

    }
}
